/*
 * @Author: yangzonglong
 * @Date: 2021-03-10 13:32:54
 * @version: v1.0.0
 * @Descripttion: Checkbox 组件
 * @LastEditors: yangzonglong
 * @LastEditTime: 2021-04-07 17:19:49
 * @Auditor: 
 */
import React, { useImperativeHandle, forwardRef, useState, useEffect } from 'react';
import { Checkbox, Form } from 'antd';
import { FormItemProps } from '../../components/components/InputFormItemController';
import { CheckboxProps as AntdCheckboxProps } from 'antd/lib/checkbox';
import useSelectDataSource from './../../hooks/useSelectDataSource';
import useQueryControlWrap from '../../hooks/useQueryControlWrap';
import { CanvasItemProps } from './../../interface';

export interface ExtendAntdCheckboxProps extends AntdCheckboxProps {
  dataSource?: Array<{ label: string; value: string; }>;
  defaultValue?: string[];
  optionWidthFlag?: boolean;
}

export interface CheckboxProps extends CanvasItemProps {
  checkboxProps?: ExtendAntdCheckboxProps;
  formItemProps?: FormItemProps;
  disabled?: boolean;
}

const CheckboxGroup = Checkbox.Group;
const FormItem = Form.Item;
const width = { width: '100%' };

interface StaticSourceRefProps {
  setSource(arr: any[]): void;
  getSource(): any[];
}

const App = (props: CheckboxProps, ref: React.Ref<StaticSourceRefProps>) => {

  const { disabled, formItemProps, checkboxProps, domComplete, ...canvasProps } = props;

  const dataSource = useSelectDataSource(checkboxProps?.dataSource);
  const [staticSource, setStaticSource] = useState<any[]>([]);

  useQueryControlWrap(canvasProps.id, formItemProps?.name, domComplete);

  const label = localStorage.i18nextLng === 'en' ? formItemProps?.labelEn : formItemProps?.label;

  useImperativeHandle(ref, () => ({
    setSource: (source: any[]) => {
      if (source) setStaticSource(source);
    },
    getSource: () => {
      return dataSource;
    }
  }));

  useEffect(() => {
    if (dataSource) {
      setStaticSource(dataSource);
    }
  }, [dataSource]);

  return (
    <FormItem {...formItemProps} {...canvasProps} initialValue={checkboxProps?.defaultValue} label={label}>
      <CheckboxGroup disabled={disabled || formItemProps?.disabled}>
        {staticSource.map((item, index) => (
          <Checkbox
            style={checkboxProps?.optionWidthFlag ? width : undefined}
            key={item.key || index}
            value={item.value}>
            { (localStorage.i18nextLng === 'en' ? item?.labelEn : item.label) || item.label}
          </Checkbox>
        ))}
      </CheckboxGroup>
    </FormItem>
  );
};

export default forwardRef(App);